import { h, Component } from 'preact'

export default class Fragment extends Component {

  constructor(options) {
    super(options);

    this.stateDataRef([]);
    this.initValue(options.el, options);
    this.initInter(options.obj, options);
  }

  initInter(obj, options) {
    obj.el = options.el || {};
    obj.getData = () => this.state.data;
    obj.setData = (val) => this.setValue(val);
    obj.addData = (val) => this.stateDataAdd(val);
    obj.delData = (i, s) => this.stateDataDel(i, s);
  }

  initValue(el, options) {
    this.setValue(el.getAttribute('data-value'));
  }

  setValue(value) {
    try {
      if (value && /^\[.*\]$/.test(value)) {
        this.stateDataRef(JSON.parse(value));
      } else if (typeof value === 'string') {
        this.stateDataRef(value.split(','));
      } else if (Array.isArray(value)) {
        this.stateDataRef(value);
      } else {
        console.log('Null');
      }
    } catch (e) {
      console.error(e);
    }
  }

  stateDataAdd(val) {
    var temp = this.state.data || [];
    var limit = this.props.limit || 999;

    // 将数据添加到栈堆 & 过滤过多的数据
    if (val && temp.push(val) && limit) {
      while (temp.length > limit) {
        temp.splice(0, 1);
      }
    }

    this.stateDataRef(temp);
  }

  stateDataDel(i, size) {
    var temp = this.state.data || [];
    if (0 <= i && i < temp.length) {
      temp.splice(i, size);
    }

    // 刷新界面显示
    this.stateDataRef(temp);
  }

  stateDataRef(data) {
    if (data && Array.isArray(data)) {
      this.setState({ data });
    } else {
      return false;
    }
  }

  onChange(e) {
    if (!e.files || e.files.length <= 0) {
      return layui.message.failure('未选择文件');
    }

    // 打开上传动画
    var uploadIndex = layui.message.loading('正在上传');

    // 构建文件名称
    var fileName = this.props.path + Date.now() + '.jpg';

    //storeAs表示上传的object name , file表示上传的文件
    this.props.oss.upload(this.props, fileName, e.files[0], (r) => {
      this.stateDataAdd(this.props.cdn + r.name);

      layui.message.close(uploadIndex);
      layui.message.success('上传成功');
    }, function (err) {
      console.error("上传失败", err);

      layui.message.close(uploadIndex);
      layui.message.failure('上传失败');
    });
  }

  render(options, state) {
    return (
      <div class="virens-aliyun-img">
        <div class="virens-aliyun-img-item input">
          <i class="layui-icon layui-icon-upload-drag"></i>
          <input type="file" accept={options.mimeType} onChange={(e) => this.onChange(e.target)} />
        </div>
        {state.data.map((url, i) => (<div class="virens-aliyun-img-item" data-src={url}>
          <img src={url} alt={url} />
          <i class="layui-icon layui-icon-delete" onClick={(e) => this.stateDataDel(i, 1)}></i>
        </div>
        ))}
      </div>
    );
  }
}